//
//  JPWebViewController.m
//  DHJPHotel
//
//  Created by 123 on 2018/5/25.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JPWebViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "UIWebView+TS_JavaScriptContext.h"
@interface JPWebViewController () <UIWebViewDelegate>
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic ,strong)NSString *access_token;
@end

@implementation JPWebViewController


- (UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
       // NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"这里是JS中alert弹出的message"];
      //  [_webView stringByEvaluatingJavaScriptFromString:@"AppBaoJie()"];
        
    }
    return _webView;
}



- (void)setUrlStr:(NSString *)urlStr
{
    _urlStr = urlStr;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    [self.view addSubview:self.webView];
//    self.webView.navigationDelegate = self;
    self.webView.delegate = self;
    self.webView.backgroundColor = UIColor.whiteColor;
    //[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    [self loadWebView];

}

- (void)loadWebView
{
    if (!DHNetworkManager.shareManager.userAccount.key) {
        // 未登录
        if ([self.urlStr rangeOfString:@"?"].location == NSNotFound) {
            self.urlStr = [NSString stringWithFormat:@"%@?comefrom=app",self.urlStr];
        }else{
            
            self.urlStr = [NSString stringWithFormat:@"%@&comefrom=app",self.urlStr];
        }
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    }else{
        
        // 已登录
        if (!DHNetworkManager.shareManager.userAccount.access_token) {
            [self requestAccessToken];
        }else{
            
            // 判断逻辑  是否为同一个用户 如果是则判断token的有效期 有效期内则直接加载网页 不是则重新请求数据
            if (!DHNetworkManager.shareManager.userAccount.lastUserID || [DHNetworkManager.shareManager.userAccount.lastUserID isEqualToString:DHNetworkManager.shareManager.userAccount.userid]) {
                
                // 同一个用户 判断time的有效期
                // 两个时间戳的间隔   返回的是秒
                float time = [self ReturnTimeWithOldTime:DHNetworkManager.shareManager.userAccount.access_token_exptime newTime:[self nowTime]];
                
                if (time > 0) {
                    //[self.webView.pasteConfigur]
                    // 有效直接加载
                    self.access_token = DHNetworkManager.shareManager.userAccount.access_token;
                    
                    
                    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@"accesstoken=%@;path/", self.access_token];
                    if ([self.urlStr rangeOfString:@"?"].location == NSNotFound) {
                        self.urlStr = [NSString stringWithFormat:@"%@?comefrom=app",self.urlStr];
                    }else{
                        
                        self.urlStr = [NSString stringWithFormat:@"%@&comefrom=app",self.urlStr];
                    }
                    // [self.reqUrl stringByReplacingOccurrencesOfString:@"http:" withString:@"https:"];
                    
                    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
                    
                    [request addValue: cookieValue forHTTPHeaderField:@"Cookie"];
                    
                    NSLog(@"添加cookie");
                    [self.webView loadRequest:request];
                }else{
                    [self requestAccessToken];
                }
            }else{
                [self requestAccessToken];
            }
        }
    }

}
- (float)ReturnTimeWithOldTime:(NSString*)oldTime newTime:(NSString*)newTime{
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];//@"yyyy-MM-dd-HHMMss"
    // 现在时间
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[newTime doubleValue]];
    NSString *dateString = [formatter stringFromDate:date];
    NSLog(@"开始时间: %@", dateString);
    // 上次返回的有效时间
    NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:[oldTime doubleValue]];
    NSString *dateString2 = [formatter stringFromDate:date2];
    NSLog(@"结束时间: %@", dateString2);
    
    NSTimeInterval seconds = [date2 timeIntervalSinceDate:date];
    NSLog(@"两个时间相隔：%f", seconds);
    
    // >0 则有效
    return seconds;
    
}
- (NSString *)nowTime{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    return timeSp;
}
- (void)requestAccessToken
{
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    dictM[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    
    NSString *url = [NSString stringWithFormat:@"%@index.php?act=member_index&op=getH5AccessToken",REMOTEURL];
    [DHNetworkManager.shareManager requestWithMethod:MethodPost
                                           UrlString:url
                                              params:dictM.copy
                                          completion:^(id json, BOOL isSuccess)
     {
         if (!isSuccess) {
             return ;
         }
         if (json[@"datas"][@"access_token"]) {
             DHNetworkManager.shareManager.userAccount.access_token = json[@"datas"][@"access_token"];
             DHNetworkManager.shareManager.userAccount.access_token_exptime = json[@"datas"][@"access_token_exptime"];
             self.access_token =  DHNetworkManager.shareManager.userAccount.access_token;
             [DHNetworkManager.shareManager.userAccount saveAccount];
             
             
             NSMutableString *cookieValue = [NSMutableString stringWithFormat:@"accesstoken=%@;path/", self.access_token];
             
             if ([self.urlStr rangeOfString:@"?"].location == NSNotFound) {
                 self.urlStr = [NSString stringWithFormat:@"%@?comefrom=app",self.urlStr];
             }else{
                 
                self.urlStr = [NSString stringWithFormat:@"%@&comefrom=app",self.urlStr];
             }
             
             NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
             
             [request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
             NSLog(@"添加cookie");
             [self->_webView loadRequest:request];
         }else{
             NSLog(@"%@",json[@"datas"][@"error"]);
         }
     }];
}
#pragma mark: - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        NSString *url;
//        if ([request.URL.absoluteString isEqualToString:@"http://jpjd.com/wap"])
//        {
//            url = [NSString stringWithFormat:@"%@?comefrom=app",request.URL.absoluteString];
//        }else{
//            url = [NSString stringWithFormat:@"%@&comefrom=app",request.URL.absoluteString];
//        }
//        if ([url isEqualToString:@"http://jpjd.cnaite.cn/wap/index.php&comefrom=app"]) {
//            return NO;
//        }
//        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
        if ([request.URL.absoluteString rangeOfString:@"?"].location == NSNotFound) {
            url = [NSString stringWithFormat:@"%@?comefrom=app",request.URL.absoluteString];
        }else{
            
            url = [NSString stringWithFormat:@"%@&comefrom=app",request.URL.absoluteString];
        }
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    }
    
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //定义好JS要调用的方法, share就是调用的share方法名
    context[@"AppBaoJie"] = ^() {
        NSLog(@"+++++++Begin Log+++++++");
        [self dismissViewControllerAnimated:true completion:nil];
        
        NSLog(@"-------End Log-------");
    };

    
}

- (void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext*)ctx
{
    ctx[@"AppLogin"] = ^() {

            NSArray *urls = [JSContext currentArguments];
            NSString *url = [(JSValue *)urls.firstObject toString];
            DHLoginController *logVC = [[DHLoginController alloc] init];
            logVC.isDismiss = YES;
            logVC.url = url;
            logVC.webLogSuccful = ^(NSString *url) {
                [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
            };
            [self presentViewController:logVC animated:true completion:nil];
        
        
    };
}




@end
